package cn.chiship.bs.api.biz.service.impl;

import cn.chiship.bs.api.biz.mapper.UpmsRoleMapper;
import cn.chiship.bs.api.biz.service.UpmsUserService;
import cn.chiship.bs.api.core.enums.LoginTypeEnum;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.encryption.Md5Util;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.bs.api.biz.entity.UpmsRole;
import cn.chiship.bs.api.biz.entity.UpmsUser;
import cn.chiship.bs.api.biz.entity.UpmsUserExample;
import cn.chiship.bs.api.biz.mapper.UpmsUserMapper;
import cn.chiship.bs.api.biz.pojo.vo.CacheRoleVo;
import cn.chiship.bs.api.biz.pojo.vo.CacheUserVO;
import cn.chiship.bs.api.biz.service.UserCacheService;
import cn.chiship.bs.api.core.util.JwtUtil;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.ChineseCharToEn;
import cn.chiship.sdk.core.util.RandomUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口服务实现
 *
 * @author lj
 */
@Service
public class UpmsUserServiceImpl extends BaseServiceImpl<UpmsUser, UpmsUserExample> implements UpmsUserService {
    @Resource
    private UserCacheService userCacheService;
    @Resource
    private UpmsUserMapper upmsUserMapper;
    @Resource
    private UpmsRoleMapper upmsRoleMapper;

    @Override
    public BaseResult insertSelective(UpmsUser upmsUser) {
        upmsUser.setPassword("11111111");
        upmsUser.setId(SnowflakeIdUtil.generateStrId());
        upmsUser.setIsLocked(BaseConstants.NO);
        upmsUser.setUserPinyin(ChineseCharToEn.getPinYinAll(upmsUser.getRealName()));
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(upmsUser.getPassword() + upmsUser.getSalt()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName());
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (!users.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }
        super.insertSelective(upmsUser);
        return BaseResult.ok("用户创建成功,初始密码为8个1");
    }

    @Override
    public BaseResult updateByPrimaryKeySelective(UpmsUser upmsUser) {
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setPassword(null);
        upmsUser.setSalt(null);
        upmsUser.setUserPinyin(ChineseCharToEn.getAllFirstLetters(upmsUser.getRealName()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName()).andIdNotEqualTo(upmsUser.getId());
        List<UpmsUser> upmsUsers = upmsUserMapper.selectByExample(upmsUserExample);
        if (!upmsUsers.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }
        super.updateByPrimaryKeySelective(upmsUser);
        return BaseResult.ok();
    }

    @Override
    public BaseResult login(String sessionId, String username, String password, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andUserNameEqualTo(username);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);
        if (!Md5Util.md5(password + user.getSalt()).equals(user.getPassword())) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, null);
        }
        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    private BaseResult login(UpmsUser user, String loginIp, String sessionId, LoginTypeEnum loginTypeEnum) {
        if (BaseConstants.YES == user.getIsLocked()) {
            return BaseResult.error(BaseResultEnum.ACCOUNT_LOCKED, null);
        }

        CacheUserVO userVO = new CacheUserVO();
        /**
         * 用户基本信息
         */
        userVO.setUserType(UserTypeEnum.ADMIN.getType());
        userVO.setMobile(user.getMobile());
        userVO.setEmail(user.getEmail());
        userVO.setUsername(user.getUserName());
        userVO.setId(user.getId());
        userVO.setRealName(user.getRealName());
        userVO.setStatus(user.getIsLocked());
        userVO.setAvatar(user.getAvatar());
        userVO.setInitPassword(user.getIsInitPassword() != 0);
        userVO.setUserCode(user.getUserCode());
        userVO.setSessionId(sessionId);

        /**
         * 用户角色
         */
        UpmsRole upmsRole = upmsRoleMapper.selectByPrimaryKey(user.getRoleId());
        List<CacheRoleVo> roleVos = new ArrayList<>();
        CacheRoleVo roleVo = new CacheRoleVo();
        roleVo.setRoleCode(upmsRole.getCode());
        roleVo.setRoleName(upmsRole.getName());
        roleVos.add(roleVo);
        userVO.setCacheRoleVos(roleVos);

        String accessToken = JwtUtil.createToken(userVO);
        userCacheService.cacheUser(accessToken, userVO);
        return BaseResult.ok(accessToken);
    }

}
